package pdf;

import generator.model.GeneratorModel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

/**
 * 
 * @author Peter Rosberg / Jenny Cahier
 *
 */
public class PdfMaker implements PdfCreator {

	public final String FONT = "C:/Windows/Fonts/Tw Cen MT Bold.ttf";
	
	private String outputFileName;
	private Document document;
	private String logoName;
	
	private PdfContentByte cb;
	private PdfWriter writer;

	// media measurements, configured for A3
	private Float docWidth = 842f;
	private Float docHeight = 1190f;
	private Float xText = 66f;
	private Float yTopTextStart = 1171f;
	private Float topPhotoHeight = 207f;
	private Float yMiddleTextStart = 791f;
	private Float yBottomTextStart = 192f;
	private Float bottomPhotoHeight = 288f;

	/**
	 * 
	 */
	public PdfMaker() {
		//standard output folder
		this("posters/GeneratedPoster.pdf");
	}
	
	/**
	 * 
	 * @param outputFileName
	 */
	public PdfMaker(String outputFileName) {
		this.outputFileName = outputFileName;
		logoName = "images/kvallsbladetLogo.jpg";
	}
	
	/**
	 * 
	 */
	public void createPDF(String sideOfferItem, 
			String sideOfferSlogan, String mainNews, 
			String mainNewsEnding, String suppelementSlogan, 
			String supplementPicture) 
			throws MalformedURLException, DocumentException, IOException {
		
		createDocument(
				sideOfferItem+" - "+sideOfferSlogan,
				mainNews,
				"-"+mainNewsEnding,
				suppelementSlogan,
				"images/topSupplement.jpg",
				supplementPicture
		);
	}
	

	/**
	 * 
	 * @param topText
	 * @param middleText
	 * @param middleTextSmall
	 * @param bottomText
	 * @param topPhotoName
	 * @param bottomPhotoName
	 * @throws DocumentException
	 * @throws MalformedURLException
	 * @throws IOException
	 */
	private void createDocument(String topText, String middleText, String middleTextSmall,  
			String bottomText, String topPhotoName, String bottomPhotoName) throws DocumentException, MalformedURLException, IOException {

		Rectangle pageSpec = new Rectangle(docWidth, docHeight); 
		// pageSpec.setBackgroundColor(new java.awt.Color(0xDF, 0xFF, 0xDE));
		document = new Document(pageSpec); // (PageSize.A3);
		writer = PdfWriter.getInstance(document, new FileOutputStream(
				outputFileName));
		document.open();
		cb = writer.getDirectContent();

		// Create top supplement
		createSmallMediaArea(topPhotoName, topPhotoHeight, docHeight
				- topPhotoHeight, topText, yTopTextStart);

		// Prints the logotype
		Image logo = Image.getInstance(logoName);
		cb.addImage(logo, docWidth, 0, 0, 176, 0, 800); // W, skeva, skeva, H, X, Y
		
		// Create middle text
		// (document, middlePhotoName, xText, xMiddleTextEnd, yMiddleTextStart,
		// yMiddleTextEnd);
		this.createNewsArea(middleText, middleTextSmall, xText, yMiddleTextStart);
		// Create bottom supplement
		

		createSmallMediaArea(bottomPhotoName, bottomPhotoHeight, 0f,
				bottomText, yBottomTextStart);

		
		
		document.close();
	}


	/**
	 * 
	 * @param textMain
	 * @param textSmaller
	 * @param x
	 * @param y
	 * @throws DocumentException
	 */
    private void createNewsArea(String textMain, String textSmaller, float x, float y) throws DocumentException {

    	PdfPTable newsTable;
    	
    	for(float fontSize=100f; 
    		(newsTable = createNewsTable(textMain, textSmaller, fontSize)).getTotalHeight() > 500f;
    		fontSize -= 5f) {
    		//Just loop until table is created which is the correct length
    	}
        
    	newsTable.writeSelectedRows(0, 10, x, y, cb);
    }

	/**
	 * Creates a table for the main news. The slogan text will always be displayed in a font
	 * which is 80% of the size of the specified font size.
	 * 
	 * This table can then be measured to see if it fits in the desired area, it it does not
	 * it can be remade, as this method does not write anything to the document.
	 *  
	 * @param textMain the main news item
	 * @param textSmaller the addon slogan
	 * @param fontSize the fontsize
	 * @return a PdfTable with a single cell containing the text in tha specified font.
	 * @throws DocumentException
	 */
    private PdfPTable createNewsTable(String textMain, String textSmaller, float fontSize) throws DocumentException {
               PdfPTable newsTable = new PdfPTable(1);
               newsTable.setTotalWidth(720);
               newsTable.setWidthPercentage(100);
               
               PdfPCell cell = new PdfPCell();

               float mainFontSize = fontSize;
               float secondFontSize = fontSize*0.8f;
               
               Font font = FontFactory.getFont(this.FONT,mainFontSize);
               Paragraph paragraph = new Paragraph(textMain, font);
               paragraph.setAlignment(Paragraph.ALIGN_JUSTIFIED_ALL);
               paragraph.setLeading(mainFontSize*1.2f);
               cell.addElement(paragraph);
               
               Font font2 = FontFactory.getFont(this.FONT,secondFontSize);
               Paragraph paragraph2 = new Paragraph(textSmaller, font2);
               paragraph2.setAlignment(Paragraph.ALIGN_JUSTIFIED);
               paragraph2.setLeading(secondFontSize*1.3f);
               cell.addElement(paragraph2);
                              
               cell.setBorder(0);
               newsTable.addCell(cell);
               System.out.println("höjd: "+newsTable.getTotalHeight()+", fontsize: "+fontSize);

               return newsTable;
    }

    /**
     * Creates the media-area that is the add-on sale or the supplement of the newspaper.
     * 
     * @param backgroundImage the file path of the background image for the area.
     * @param backgroundImageHeight the height of the background image
     * @param yBackgroundImage the y-coordinate to place the background image at
     * @param text the text to display in the media area
     * @param yTextStart the y-coordinate at which to start printing the text
     * @throws MalformedURLException
     * @throws IOException
     * @throws DocumentException
     */
	private void createSmallMediaArea(String backgroundImage, Float backgroundImageHeight,
			Float yBackgroundImage, String text, Float yTextStart)
			throws MalformedURLException, IOException, DocumentException {


		// create photo and set properties
		Image photo = Image.getInstance(backgroundImage);
		// Places images and makes text go on top
		photo.setAlignment(Image.UNDERLYING); 

		cb.addImage(photo, docWidth, 0, 0, backgroundImageHeight, 0, yBackgroundImage); 

		// ----  Text area  -----
    	PdfPTable newsTable;
    	
    	for(float fontSize=80f; 
    		(newsTable = createSupplementTable(text, fontSize)).getTotalHeight() > 150f;
    		fontSize -= 5f) {
    		//Just loop until table is created which is the correct length
    	}
        
    	newsTable.writeSelectedRows(0, 10, xText, yTextStart, cb);
		

	}
	
	/**
	 * Create a table for the smaller news areas (supplement and add-on sales).
	 * This table can then be measured to see if it fits in the desired area, it it does not
	 * it can be remade, as this method does not write anything to the document.
	 * 
	 * @param textMain the text to display in the media area
	 * @param fontSize the size of the font in points
	 * @return
	 * @throws DocumentException
	 */
    private PdfPTable createSupplementTable(String textMain, float fontSize) throws DocumentException {
               PdfPTable newsTable = new PdfPTable(1);
               newsTable.setTotalWidth(420);
               newsTable.setWidthPercentage(100);
               
               PdfPCell cell = new PdfPCell();
               
               Font font = FontFactory.getFont(this.FONT,fontSize);
               Paragraph paragraph = new Paragraph(textMain, font);
               //paragraph.setAlignment(paragraph.ALIGN_JUSTIFIED_ALL);
               cell.addElement(paragraph);
                              
               cell.setBorder(0);
               newsTable.addCell(cell);
               System.out.println("mini-höjd: "+newsTable.getTotalHeight()+", fontsize: "+fontSize);

               return newsTable;
    }


			
	/**
	 * Starts the pdfmaker and performs a quick test of it.
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		PdfCreator pdf = new PdfMaker();
		
		String[] feeds = 
		{
			"http://nyheter24.se/nyheter/?feed=true&feedArticles=all",
			"http://www.nyhetsportalen.se/?t=640&rss=1&na=15"
		};
		GeneratorModel model = new GeneratorModel(pdf, feeds);

		model.updateAll(false);
		model.createPDF();
		
		System.out.println("Created test-pdf!");
		
		Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler posters\\GeneratedPoster.pdf");

	}

}
